package com.yfbao.horizon.encrypt.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

/**
 * AES加密与解密工具类
 * 对称加密
 */
@Slf4j
public class AESUtils {
    static final String AES = "AES";
    static final String EN_CODING = "UTF-8";
    static final String SHA1_PRNG = "SHA1PRNG";
    static final String DEFAULT_CHIPHER_INSTANCE = "AES/CBC/PKCS5Padding";

    static final IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());

    public static final int DEFAULT_KEY_SIZE = 128;

    /**
     * 加密
     *
     * @param clearText 明文
     * @param key       加解密密钥
     * @return String 密文-XX:NativeMemoryTracking=detail
     */
    public static String encrypt(String clearText, String key) {
        return encrypt(clearText, key, DEFAULT_KEY_SIZE);
    }

    /**
     * 加密
     *
     * @param clearText 明文
     * @param key       加解密密钥
     * @param keySize   密钥长度
     * @return String 密文
     */
    public static String encrypt(String clearText, String key, int keySize) {
        try {
            return encrypt(clearText.getBytes(EN_CODING), key, keySize);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密
     *
     * @param clearText 明文
     * @param key       加解密密钥
     * @return String 密文
     */
    public static String encrypt(byte[] clearText, String key) {
        return encrypt(clearText, key, DEFAULT_KEY_SIZE);
    }

    /**
     * 加密
     *
     * @param clearText 明文
     * @param key       加解密密钥
     * @param keySize   密钥长度
     * @return String 密文
     */
    public static String encrypt(byte[] clearText, String key, int keySize) {
        try {
            StringBuffer sb = new StringBuffer();
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            SecureRandom random = SecureRandom.getInstance(SHA1_PRNG);
            random.setSeed(key.getBytes());
            kgen.init(keySize, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, AES);
            Cipher cipher = Cipher.getInstance(DEFAULT_CHIPHER_INSTANCE);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
            byte[] byteResult = cipher.doFinal(clearText);
            for (int i = 0; i < byteResult.length; i++) {
                String hex = Integer.toHexString(byteResult[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密
     *
     * @param cipherText 密文
     * @param key        加解密密钥
     * @param keySize    密钥长度
     * @return String 明文
     */
    public static String decrypt(String cipherText, String key, int keySize) {
        return new String(decrypt2Byte(cipherText, key, keySize));
    }

    /**
     * 解密
     *
     * @param cipherText 密文
     * @param key        加解密密钥
     * @return String 明文
     */
    public static String decrypt(String cipherText, String key) {
        return new String(decrypt2Byte(cipherText, key));
    }

    /**
     * 解密
     *
     * @param cipherText 密文
     * @param key        加解密密钥
     * @return String 明文
     */
    public static byte[] decrypt2Byte(String cipherText, String key) {
        return decrypt2Byte(cipherText, key, DEFAULT_KEY_SIZE);
    }

    /**
     * 解密
     *
     * @param cipherText 密文
     * @param key        加解密密钥
     * @param keySize    密钥长度
     * @return String 明文
     */
    public static byte[] decrypt2Byte(String cipherText, String key, int keySize) {
        try {
            byte[] byteResult = new byte[cipherText.length() / 2];
            for (int i = 0; i < cipherText.length() / 2; i++) {
                int high = Integer.parseInt(cipherText.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(cipherText.substring(i * 2 + 1, i * 2 + 2), 16);
                byteResult[i] = (byte) (high * 16 + low);
            }
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            SecureRandom random = SecureRandom.getInstance(SHA1_PRNG);
            random.setSeed(key.getBytes());
            kgen.init(keySize, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, AES);
            Cipher cipher = Cipher.getInstance(DEFAULT_CHIPHER_INSTANCE);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
            return cipher.doFinal(byteResult);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
